package com.gem.talkbase.activity;

//================================主要功能：登录activity=====================================

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jivesoftware.smack.packet.Presence;
import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import com.gem.talkbase.R;
import com.gem.talkbase.service.JSON_me;
import com.gem.talkbase.util.MyTextWatcher;
import com.gem.talkbase.util.RotationHelper;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.constant.Constants;
import com.gem.talkbase.util.XmppTool;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;




public class LoginActivity extends FinalActivity {

	/**
	 * 根布局
	 */
	private List<Firend> list;
	private String uname,upass;
	public ViewGroup mTranslateLayoutContainer;  
	String tag;  
	String requestPath=Client.Login_URL;
	@ViewInject(id=R.id.signin_button,click="btn")Button login;//登录
	@ViewInject(id=R.id.register_btn,click="register")Button register;//注册
	@ViewInject(id=R.id.username)EditText username ;
	@ViewInject(id=R.id.password)EditText password ;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		register = (Button) findViewById(R.id.register_btn);
		login = (Button) findViewById(R.id.signin_button);
		username = (EditText) findViewById(R.id.username);	
		username.addTextChangedListener(new NewWatcher());
		password = (EditText) findViewById(R.id.password);
		password.addTextChangedListener(new NewWatcher());
		showView(); 

		mTranslateLayoutContainer = (ViewGroup) findViewById(R.id.layout_login);  
		mTranslateLayoutContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
		login.setOnClickListener(new View.OnClickListener() {


			@Override
			public void onClick(View v) {
				System.out.println("监听开始！");
				uname = LoginActivity.this.username.getText().toString();
				upass = LoginActivity.this.password.getText().toString();
				System.out.println(uname+"+======"+upass);
				Login(uname,upass);

				System.out.println("监听结束！");	

			}	
		});

		register.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				rotateHelper = new RotationHelper( LoginActivity.this, Constants.KEY_FIRST_INVERSE);  //1
				rotateHelper.applyFirstRotation(mTranslateLayoutContainer, 0, -90);  //0---->-92

			}	
		});
	}
	RotationHelper rotateHelper;  
	public void showView() {  
		Bundle bundle = this.getIntent().getExtras();   
		if (bundle != null) {  
			tag = bundle.getString("second");  
			System.out.println("tag =================================>>>>" + tag);  
			if (tag.equals("Second")) {  
				mTranslateLayoutContainer = (LinearLayout) findViewById(R.id.layout_login);  
				// 因为要旋转所以我们需要保存视图的缓存信息 
				mTranslateLayoutContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
				rotateHelper = new RotationHelper(this,Constants.KEY_FIRST_CLOCKWISE);  //2
				rotateHelper.applyLastRotation(mTranslateLayoutContainer, -88, 0);  //-88=====>0
			}  
		}   
	}     

	// 登录
	public void Login(final String username, final String password) {
		AjaxParams params = new AjaxParams();
		params.put("username", username);
		params.put("password", password);
		FinalHttp fh = new FinalHttp();  
		fh.post(requestPath, params, new AjaxCallBack<String>() {
			@Override
			public void onFailure(Throwable t, String strMsg) {
				System.out.println("加载失败！！！");
				super.onFailure(t, strMsg);
			}

			@Override 
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				System.out.println("正在加载！！！");
				super.onLoading(count, current);
			}


			public void onSuccess(String jsonString) {
				super.onSuccess(jsonString);
				System.out.println(jsonString.toString()+"***********************"+jsonString.length());
				//==================判断输入不正确，弹出对话框===================================
				if(jsonString.toString().length()==2){
					AlertDialog.Builder builder = new Builder(LoginActivity.this);
					builder.setMessage("用户名或密码输入错误，请重新输入！");
					builder.setTitle("输入提示");
					builder.setPositiveButton("确定", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

							dialog.dismiss();
						}
					}).show();
				}		//==================判断输入是否正确，正确就跳转===================================
				else if(jsonString.toString().length()>1){		
					list=new ArrayList<Firend>();
					try {
						JSON_me json_me =new JSON_me();
						list=json_me.fun(jsonString);
						Iterator<Firend> iterator=list.iterator();
						Firend firend = null;
						String name = null;
						String userimage = null;
						while(iterator.hasNext()){ 
							firend=iterator.next(); 
							name=firend.getUsername();
							userimage=firend.getUimage();	
						}   
						SharedPreferences sharedPreferences = getSharedPreferences(Client.SAVE_USER, MODE_PRIVATE); 
						Editor editor = sharedPreferences.edit();//获取编辑器 
						editor.putString("username", name);  //登录昵称
						editor.putString("userid", username);//登录手机号
						editor.putString("password", upass); //登录密码
						editor.putString("userimage", userimage);//登录头像
						editor.commit();//提交修改 
						System.out.println(name+"==========="+upass+"======="+userimage); 

						Thread t=new Thread(new Runnable() {	 		  	
							public void run() {	
								try {
									System.out.println(username+"====================="+password);	    	 
									//登录第三方服务器==============================
									XmppTool.getConnection().login(username, password);
									System.out.println("22222222222222222222xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");	 
									System.out.println(username+"())()()()()()()()"+password);
									Presence presence = new Presence(Presence.Type.available);
									XmppTool.getConnection().sendPacket(presence);
									System.out.println("1111111111111=======================================");
									Intent service = new Intent(LoginActivity.this,ChatMessageService.class);
									startService(service);
									System.out.println("2222222222222=======================================");
									Intent intent =new Intent(LoginActivity.this,MainActivity.class);
									intent.putExtra("username",username);
									startActivity(intent);
									LoginActivity.this.finish();
								} catch (Exception e) { 
									//    XmppTool.closeConnection();
								}finally{

								}
							}
						});
						t.start();		


					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}	
			}
		});

	}
	//点击注册按钮
	public void register(View v){
		//			//点击注册Button实现跳转
		//			        Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
		//			        this.startActivityForResult(intent, 30);
		//		Intent intent = new Intent(this,RegisterActivity.class);
		//		startActivityForResult(intent, 1);
		//		System.out.println("已跳转到RegisterActivity");

		//	     mTranslateLayoutContainer = (ViewGroup) findViewById(R.id.layout_login);  
		//         mTranslateLayoutContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
		// 
		//		rotateHelper = new RotationHelper(LoginActivity.this, Constants.KEY_FIRST_INVERSE);  
		//	    rotateHelper.applyFirstRotation(mTranslateLayoutContainer, 0, 90);  //0->-92

	}
	//============================== 旋转的速度控制===================================================
	public void jumpToSecond() {  
		Intent in = new Intent();  
		in.setClass(LoginActivity.this, RegisterActivity.class); 
		in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);         
		Bundle bundle = new Bundle();  
		bundle.putString("front", "First");   
		in.putExtras(bundle);     
		//startActivity(in);  
		startActivityForResult(in, 1);
		overridePendingTransition(R.anim.fade, R.anim.hold);
		//overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit); 
		//overridePendingTransition(R.anim.rotate_middle_y_in, R.anim.rotate_middle_y_out);
	}  


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if(requestCode==1&&resultCode==RESULT_OK){
			String nameBack = data.getStringExtra("userName");
			System.out.println("================"+nameBack+"---------");
			username.setText(nameBack); 

		}   
	}


	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
		System.exit(0);

	}






	//===========================监控EditText输入===================================
	public class NewWatcher extends MyTextWatcher {

		@Override //文字变化时  
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String  uname = LoginActivity.this.username.getText().toString();
			String 	upass = LoginActivity.this.password.getText().toString();

			//==================如果输入框里面有值，则可以点击=======================
			if(uname.length()>0&&upass.length()>0){
				login.setEnabled(true);
				login.setBackgroundResource(R.drawable.blue_button4);
				System.out.println(uname+"________________"+upass);
				//==================如果输入框里面没有值，则不可以点击=======================
			}else{
				login.setEnabled(false); 
				login.setBackgroundResource(R.drawable.blue_button);
				System.out.println(uname+"---------"+upass); 
			} 
		}

		@Override//文字变化前  
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			//	 System.out.println("beforeTextChanged--" + username.getText().toString()+"???????"+password.getText().toString());
		}



		@Override//文字变化后  
		public void afterTextChanged(Editable s) {
			// System.out.println("afterTextChanged--" + username.getText().toString()+"???????"+password.getText().toString());

		}

	}

}
